package com.smsc.headend.task.engine.handler.impl.collection.builder;

import com.smsc.headend.task.engine.exception.UDISTaskHandlerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class BuildScheduleReadResultFactory {
    private Map<Long, Class<ScheduleReadBuilder>> scheduleReadHandleResultMap = new HashMap<>();
    @Autowired
    AutowireCapableBeanFactory autowireCapableBeanFactory;

    @PostConstruct
    public void init() {
        this.registerHandler(ScheduleReadEnum.PHASE_RECOGNITION.getDataItemId(), PhaseRecognitionResultHandler.class);
        this.registerHandler(ScheduleReadEnum.PLC_NETWORK_TOPOLOGY_INFO.getDataItemId(), PlcNetworkTopoInfoHandler.class);
    }

    public ScheduleReadBuilder buildScheduleReadResult(Long dataItemId) throws UDISTaskHandlerException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {

        Class<ScheduleReadBuilder> taskHandlerClass = this.scheduleReadHandleResultMap.get(dataItemId);
        if (taskHandlerClass != null) {

            ScheduleReadBuilder scheduleReadBuilder = taskHandlerClass.getDeclaredConstructor().newInstance();
            autowireCapableBeanFactory.autowireBean(scheduleReadBuilder);
            return scheduleReadBuilder;
        } else {
            //表计数据项
            ScheduleReadGeneralHandler scheduleReadGeneralHandler =
                    ScheduleReadGeneralHandler.class.getDeclaredConstructor().newInstance();
            autowireCapableBeanFactory.autowireBean(scheduleReadGeneralHandler);
            return scheduleReadGeneralHandler;
        }
    }

    public Boolean registerHandler(Long subDataItemId, Class scheduleReadHandler) {
        if (scheduleReadHandleResultMap.containsKey(subDataItemId)) {
            return false;
        }
        scheduleReadHandleResultMap.put(subDataItemId, scheduleReadHandler);
        return true;
    }
}